问题背景
由于QueryRender是直接将数据塞进Render()里的
handleUpdate = (hasNextPage, xdata) =>{ console.log(3); const data = this.state.data.concat(xdata); this.setState({ data: data, loadingMore: false, hasNextPage: hasNextPage }, () => { window.dispatchEvent(new Event('resize')); }); } render(){ return({ if (error) { console.log(error) } if (!props) { return ( ) } this.handleUpdate(props.bookList.hasNextPage, props.bookList.edges); const loadMore = this.state.hasNextPage ? ( {this.state.loadingMore &&) : null; const mydata = this.state.data.concat(props.bookList.edges); return (} {!this.state.loadingMore && } ) }} /> ) }
直接在render里进行setState会导致组件无限循环渲染,当然把queryrender取缔掉用fetch替换可以解决,但是怎么在使用relay的同时直接setState呢?
改进一:
export default class SearchList extends PureComponent{ state={ after: "", data: [], } updateAfter = (after, xdata) =>{ const data = this.state.data.concat(xdata); this.setState({after: after, data: data}, () =>{ window.dispatchEvent(new Event('resize')); }); } render(){ return({ if (error) { console.log(error) } return ( this.updateAfter(props.bookList.pageInfo.endCursor, props.bookList.edges)} hasNextPage={props ? props.bookList.pageInfo.hasNextPage : null} dataSource={props ? this.state.data.concat(props.bookList.edges) : this.state.data}/> ) }} /> ) }}class SearchListComponent extends PureComponent{ constructor(props){ super(props) } componentWillReceiveProps = (nextProps) =>{ console.log(1) window.dispatchEvent(new Event('resize')); } render(){ const loadMore = this.props.hasNextPage ? ( {this.props.loadingMore &&) : null; return(} {!this.props.loadingMore && }
缺陷:点击加载更多会闪一下,因为render会走两遍,第一遍是加载中,return null